import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Settings, Lightbulb, CheckCircle, AlertTriangle } from 'lucide-react';
import { ConstructionMethodTemplate } from '@/api/entities';

export default function ConstructionMethodStep({ data, onUpdate }) {
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [recommendations, setRecommendations] = useState([]);
  const [isAnalyzing, setIsAnalyzing] = useState(false);

  useEffect(() => {
    loadMethodTemplates();
  }, []);

  useEffect(() => {
    if (data.crossingType && data.spanLength) {
      generateRecommendations();
    }
  }, [data.crossingType, data.spanLength, data.crossingHeight]);

  const loadMethodTemplates = async () => {
    try {
      const templates = await ConstructionMethodTemplate.list();
      setMethodTemplates(templates);
    } catch (error) {
      console.error("加载施工方法模板失败:", error);
    }
  };

  const generateRecommendations = () => {
    setIsAnalyzing(true);
    
    // 模拟AI分析推荐
    setTimeout(() => {
      const methods = [];
      const spanLength = parseFloat(data.spanLength) || 0;
      const crossingHeight = parseFloat(data.crossingHeight) || 0;
      
      // 基于跨越类型和参数推荐方法
      switch (data.crossingType) {
        case 'highway':
          if (spanLength > 150) {
            methods.push({
              method: 'helicopterStringing',
              score: 90,
              reasoning: '高速公路跨越，档距较大，直升机施工效率高，对交通影响小',
              advantages: ['施工速度快', '对交通影响最小', '安全性高'],
              disadvantages: ['成本较高', '天气要求严格'],
              suitability: '非常适合'
            });
            methods.push({
              method: 'droneStringing',
              score: 75,
              reasoning: '无人机牵引适用于中等档距，成本适中',
              advantages: ['成本适中', '操作灵活', '对交通影响小'],
              disadvantages: ['受风力影响大', '载重有限'],
              suitability: '适合'
            });
          } else {
            methods.push({
              method: 'scaffoldingErection',
              score: 85,
              reasoning: '档距较小，搭设跨越架经济实用',
              advantages: ['成本低', '技术成熟', '施工稳定'],
              disadvantages: ['需要交通管制', '施工周期长'],
              suitability: '适合'
            });
          }
          break;

        case 'railway':
          methods.push({
            method: 'helicopterStringing',
            score: 95,
            reasoning: '铁路跨越安全要求极高，直升机施工最安全',
            advantages: ['安全性最高', '对铁路运营无影响', '施工速度快'],
            disadvantages: ['成本最高', '天气依赖性强'],
            suitability: '强烈推荐'
          });
          methods.push({
            method: 'rocketStringing',
            score: 80,
            reasoning: '火箭炮牵引可在铁路停运时间窗口内完成',
            advantages: ['速度极快', '技术成熟', '精度高'],
            disadvantages: ['需要停运配合', '设备昂贵'],
            suitability: '适合'
          });
          break;

        case 'river':
          if (spanLength > 300) {
            methods.push({
              method: 'helicopterStringing',
              score: 95,
              reasoning: '大跨度河流跨越，直升机是最佳选择',
              advantages: ['适应大跨度', '不受水位影响', '施工灵活'],
              disadvantages: ['成本高', '天气敏感'],
              suitability: '强烈推荐'
            });
          } else {
            methods.push({
              method: 'cableCraneStringing',
              score: 80,
              reasoning: '中等跨度河流，索道展放经济适用',
              advantages: ['成本适中', '技术成熟', '可靠性高'],
              disadvantages: ['受季节影响', '需要水上作业'],
              suitability: '适合'
            });
          }
          break;

        case 'power_line':
          methods.push({
            method: 'helicopterStringing',
            score: 92,
            reasoning: '电力线路跨越，直升机展放避免停电影响',
            advantages: ['无需停电', '安全可靠', '效率高'],
            disadvantages: ['成本较高', '天气条件要求'],
            suitability: '推荐'
          });
          break;

        default:
          methods.push({
            method: 'scaffoldingErection',
            score: 75,
            reasoning: '常规跨越采用搭设跨越架较为经济',
            advantages: ['成本低', '技术成熟', '施工稳定'],
            disadvantages: ['施工周期长', '占用场地'],
            suitability: '适合'
          });
      }

      setRecommendations(methods.sort((a, b) => b.score - a.score));
      setIsAnalyzing(false);
    }, 1500);
  };

  const handleMethodChange = (methodCode) => {
    const template = methodTemplates.find(t => t.methodCode === methodCode);
    setSelectedTemplate(template);
    
    onUpdate({
      constructionMethod: methodCode,
      methodReasoning: template?.description || ''
    });
  };

  const handleReasoningChange = (value) => {
    onUpdate({ methodReasoning: value });
  };

  const getMethodLabel = (method) => {
    const labels = {
      helicopterStringing: '直升机展放',
      droneStringing: '无人机牵引',
      rocketStringing: '火箭炮牵引',
      cableCraneStringing: '索道展放',
      scaffoldingErection: '搭设跨越架',
      manualStringing: '人工架线',
      vehicleStringing: '车辆牵引'
    };
    return labels[method] || method;
  };

  const getSuitabilityColor = (suitability) => {
    const colors = {
      '强烈推荐': 'bg-green-100 text-green-800 border-green-200',
      '推荐': 'bg-blue-100 text-blue-800 border-blue-200',
      '非常适合': 'bg-purple-100 text-purple-800 border-purple-200',
      '适合': 'bg-yellow-100 text-yellow-800 border-yellow-200'
    };
    return colors[suitability] || 'bg-gray-100 text-gray-800 border-gray-200';
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3 mb-6">
        <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
          <Settings className="w-6 h-6 text-green-600" />
        </div>
        <div>
          <h2 className="text-xl font-bold text-gray-900">施工方法选择</h2>
          <p className="text-gray-600">基于工程特点选择最适合的施工方法</p>
        </div>
      </div>

      {/* AI推荐方法 */}
      {recommendations.length > 0 && (
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <Lightbulb className="w-5 h-5 text-orange-500" />
            <h3 className="text-lg font-semibold text-gray-800">AI智能推荐</h3>
          </div>
          
          {isAnalyzing ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <p className="text-gray-600">正在分析最佳施工方法...</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {recommendations.map((rec, index) => (
                <Card key={rec.method} className={`cursor-pointer transition-all duration-200 ${
                  data.constructionMethod === rec.method 
                    ? 'border-blue-500 bg-blue-50' 
                    : 'hover:border-gray-300'
                }`} onClick={() => handleMethodChange(rec.method)}>
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between">
                      <div>
                        <CardTitle className="text-base flex items-center gap-2">
                          {getMethodLabel(rec.method)}
                          {index === 0 && <Badge className="bg-orange-100 text-orange-700">最佳</Badge>}
                        </CardTitle>
                        <Badge variant="outline" className={getSuitabilityColor(rec.suitability)}>
                          {rec.suitability}
                        </Badge>
                      </div>
                      <div className="text-right">
                        <div className="text-lg font-bold text-green-600">{rec.score}%</div>
                        <div className="text-xs text-gray-500">匹配度</div>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <p className="text-sm text-gray-600 mb-3">{rec.reasoning}</p>
                    
                    <div className="grid md:grid-cols-2 gap-3">
                      <div>
                        <h5 className="text-xs font-medium text-green-700 mb-1">优势</h5>
                        <ul className="text-xs text-gray-600 space-y-1">
                          {rec.advantages.map((adv, i) => (
                            <li key={i} className="flex items-center gap-1">
                              <CheckCircle className="w-3 h-3 text-green-500" />
                              {adv}
                            </li>
                          ))}
                        </ul>
                      </div>
                      
                      <div>
                        <h5 className="text-xs font-medium text-orange-700 mb-1">注意事项</h5>
                        <ul className="text-xs text-gray-600 space-y-1">
                          {rec.disadvantages.map((dis, i) => (
                            <li key={i} className="flex items-center gap-1">
                              <AlertTriangle className="w-3 h-3 text-orange-500" />
                              {dis}
                            </li>
                          ))}
                        </ul>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      )}

      {/* 手动选择方法 */}
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-800">手动选择施工方法</h3>
        <div>
          <Label htmlFor="constructionMethod">施工方法 *</Label>
          <Select
            value={data.constructionMethod}
            onValueChange={handleMethodChange}
          >
            <SelectTrigger>
              <SelectValue placeholder="选择施工方法" />
            </SelectTrigger>
            <SelectContent>
              {methodTemplates.map(template => (
                <SelectItem key={template.methodCode} value={template.methodCode}>
                  {template.methodName} - ({template.methodCode})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          
          {selectedTemplate && (
            <div className="mt-2 p-3 bg-blue-50 rounded-lg border border-blue-200">
              <p className="text-sm text-blue-800">
                <strong>模板说明：</strong>{selectedTemplate.description}
              </p>
              {selectedTemplate.applicableScenarios && selectedTemplate.applicableScenarios.length > 0 && (
                <p className="text-sm text-blue-700 mt-1">
                  <strong>适用场景：</strong>{selectedTemplate.applicableScenarios.join('、')}
                </p>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 方法选择理由 */}
      <div>
        <Label htmlFor="methodReasoning">方法选择理由</Label>
        <Textarea
          id="methodReasoning"
          value={data.methodReasoning}
          onChange={(e) => handleReasoningChange(e.target.value)}
          placeholder="说明选择此施工方法的原因和依据..."
          rows={4}
        />
      </div>
    </div>
  );
}